/**
 * @author ThanhNgo
 * @date Dec 10, 2013
 *
 */
package com.bestbuy.daoimple;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bestbuy.dao.AccountDao;
import com.bestbuy.pojo.Account;
import com.bestbuy.pojo.AccountInfo;
import com.bestbuy.pojo.AccountRole;
import com.bestbuy.util.AccountUtil;

/**
 * @author ThanhNgo
 *
 */

@Repository
@SuppressWarnings({"unchecked", "rawtypes"})
public class AccountDaoImpl implements AccountDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	public AccountInfo getInfoAccount(Account account)
	{
		return null;
	}
	
	public AccountRole getRoleAccount(Account account){
		return null;
	}
	
	/* 
	 * author ThanhNgo
	 */
	public List<Account> getListAccount() {
		// TODO Auto-generated method stub
		return null;
	}
	
	

	/* 
	 * author ThanhNgo
	 */
	public Account Register(String username, String password)
	{
		Session session = sessionFactory.getCurrentSession();
		// kiem tra xem user nay co ton tai chua
		String hql = "select user from Account user where username = ?";
		Query query = session.createQuery(hql);
		query.setString(0, username);
		Account account = (Account) query.uniqueResult();
		if (account != null) // user nay` da ton tai
		{
			return null;
		}
		else
		{
			// khoi tao account
			account.setUsername(username);
			account.setPassword(AccountUtil.md5(password));
			// luu account lai
			session.save(account);
			return account;
		}
	}

	/* 
	 * author ThanhNgo
	 */
	public Account getAccount(String username, String password) {
		// TODO Auto-generated method stub
		String passMD5 = AccountUtil.md5(password);
		Session session = sessionFactory.getCurrentSession();
		String sql = "from Account where username = ? and password = ?";
		Query query = session.createQuery(sql);
		query.setString(0, username);
		query.setString(1, passMD5);
		Account acc = (Account) query.uniqueResult();
		return acc;
	}

	/* 
	 * author ThanhNgo
	 */
	public Account authenticate(String username, String password) {
		// TODO Auto-generated method stub
		String passMD5 = AccountUtil.md5(password);
		Session session = sessionFactory.getCurrentSession();
		String sql = "from Account where username = ? and password = ? and isdeleted = ?";
		Query query = session.createQuery(sql);
		query.setString(0, username);
		query.setString(1, passMD5);
		query.setInteger(2, 1);
		Account acc = (Account) query.uniqueResult();
		return acc;
	}

}
